<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-shopping-cart-full"></i> 活动订单管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 搜索栏 -->
    <div class="container">
      <div class="handle-box">
        <el-input v-model="searchForm.activityTitle" placeholder="活动名称" class="handle-input mr10 mb10" clearable />
        <el-input v-model="searchForm.orderTradeId" placeholder="订单号" class="handle-input mr10" clearable />
        <el-input v-model="searchForm.participantsName" placeholder="参与人名" class="handle-input mr10" clearable />
        <el-input v-model="searchForm.userId" placeholder="用户ID" class="handle-input mr10" clearable />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="showAddOrder">新增订单</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border class="table" ref="orderTable" header-cell-class-name="table-header">
        <el-table-column prop="id" label="ID" width="80">
          <template #default="scope">
            {{ scope.row.id || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="orderTradeId" label="订单号" width="150">
          <template #default="scope">
            {{ scope.row.orderTradeId || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="tradeGoods" label="活动ID" width="80" />
        <el-table-column prop="tradeGoodsName" label="活动名称" width="200">
          <template #default="scope">
            {{ scope.row.tradeGoodsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="tradeUser" label="购买者ID" />
        <el-table-column label="参与人信息" width="150">
          <template #default="scope">
            <div v-if="scope.row.mobile">
              <div>手机: {{ scope.row.mobile }}</div>
              <div class="participant-count">
                参与人数: {{ getParticipantCount(scope.row) }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="tradeInfo" label="订单信息">
          <template #default="scope">
            <div class="order-info">{{ scope.row.tradeInfo || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="价格信息">
          <template #default="scope">
            <div>单价: ¥{{ scope.row.tradePrice || 0 }}</div>
            <div>数量: {{ scope.row.tradeNumber || 0 }}</div>
            <div class="total-price">总价: ¥{{ scope.row.tradeMoney || 0 }}</div>
          </template>
        </el-table-column>
        <el-table-column label="支付状态">
          <template #default="scope">
            <el-tag :type="getPayStatusType(scope.row.tradeStatus)">
              {{ getPayStatusText(scope.row.tradeStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" width="100">
          <template #default="scope">
            {{ getPayWayText(scope.row.payWay) }}
          </template>
        </el-table-column>
        <el-table-column label="核销状态">
          <template #default="scope">
            <el-tag :type="getWriteOffStatusType(scope.row.writeOffStatus)">
              {{ getWriteOffStatusText(scope.row.writeOffStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="核销码" width="120">
          <template #default="scope">
            <el-button type="primary" v-if="scope.row.tradeStatus === 1 && scope.row.writeOffStatus === 0"
              @click="showWriteOffCode(scope.row)" size="small">
              查看
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="支付时间">
          <template #default="scope">
            {{ scope.row.payTime ? dateFormat(scope.row.payTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="showEditOrder(scope.row)">编辑</el-button>
            <el-button type="text" @click="showEditParticipants(scope.row)">修改参与人</el-button>
            <!-- <el-button type="text" @click="handleVerify(scope.row)"
              :disabled="scope.row.writeOffStatus === 1 || scope.row.tradeStatus !== 1">核销</el-button> -->
            <el-button type="text" class="red" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑订单弹窗 -->
    <el-dialog v-model="orderDialog.visible" :title="orderDialog.isEdit ? '编辑订单' : '新增订单'" width="800px">
      <el-form :model="orderDialog.form" :rules="orderRules" ref="orderForm" label-width="120px">
        <el-form-item label="活动" prop="activityId">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input v-model="selectedActivityDisplay" placeholder="请选择活动" readonly style="flex: 1;" />
            <el-button @click="showSelectActivity">选择活动</el-button>
            <el-button v-if="selectedActivity" @click="clearActivity" type="danger">清除</el-button>
          </div>
        </el-form-item>
        <el-form-item label="购买者" prop="buyerId">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input v-model="selectedUserDisplay" placeholder="请选择购买者" readonly style="flex: 1;" />
            <el-button @click="showSelectUser">选择购买者</el-button>
            <el-button v-if="selectedUser" @click="clearUser" type="danger">清除</el-button>
          </div>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="orderDialog.form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="支付状态" prop="payStatus">
          <el-select v-model="orderDialog.form.payStatus" placeholder="请选择支付状态">
            <el-option label="待支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="已取消" :value="2" />
            <el-option label="已退款" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="orderDialog.form.payStatus === 1" label="支付时间" prop="payTime">
          <el-date-picker v-model="orderDialog.form.payTime" type="datetime" placeholder="选择支付时间" />
        </el-form-item>
        <el-form-item v-if="orderDialog.form.payStatus === 1" label="支付方式" prop="payWay">
          <el-select v-model="orderDialog.form.payWay" placeholder="请选择支付方式">
            <el-option label="支付宝" :value="1" />
            <el-option label="微信" :value="2" />
            <el-option label="衫德" :value="3" />
            <el-option label="余额" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款状态" prop="refundStatus">
          <el-select v-model="orderDialog.form.refundStatus" placeholder="请选择退款状态">
            <el-option label="未申请" :value="0" />
            <el-option label="已申请" :value="1" />
            <el-option label="已退款" :value="2" />
            <el-option label="拒绝" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="orderDialog.form.refundStatus !== 0" label="退款时间" prop="refundTime">
          <el-date-picker v-model="orderDialog.form.refundTime" type="datetime" placeholder="选择退款时间" />
        </el-form-item>
        <el-form-item label="订单信息" prop="tradeInfo">
          <el-input v-model="orderDialog.form.tradeInfo" type="textarea" rows="3" placeholder="请输入订单信息" />
        </el-form-item>
        <el-form-item label="数量" prop="tradeNumber">
          <el-input-number v-model="orderDialog.form.tradeNumber" :min="1" @change="calculateTotal" />
          <div v-if="totalPrice > 0" class="total-display">
            总价: <span class="total-price">¥{{ totalPrice }}</span>
          </div>
        </el-form-item>
        <el-form-item label="订单创建时间" prop="tradeTime">
          <el-date-picker v-model="orderDialog.form.tradeTime" type="datetime" placeholder="选择创建时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="orderDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveOrder">保存</el-button>
      </template>
    </el-dialog>

    <!-- 订单参与人对话框 -->
    <order-participant-dialog v-model="participantDialog.visible" :order-id="participantDialog.orderId"
      :order-trade-id="participantDialog.orderTradeId" :votes-goods="participantDialog.votesGoods" />

    <!-- 选择活动弹窗 -->
    <select-activity v-model="selectActivityVisible" :selected-data="selectedActivity"
      @confirm="handleActivitySelect" />

    <!-- 选择用户弹窗 -->
    <select-user v-model="selectUserVisible" :multiple="false"
      :selected-user-ids="selectedUser ? [selectedUser.userId] : []" @confirm="handleUserSelect" />

    <!-- 核销码预览弹窗 -->
    <el-dialog v-model="qrCodePreviewDialog.visible" title="核销码" width="400px" center>
      <div class="qr-code-preview">
        <img :src="qrCodePreviewDialog.imageUrl" alt="核销码" />
      </div>
      <template #footer>
        <el-button @click="qrCodePreviewDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="handleWriteOff" :loading="writeOffLoading">
          核销
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { getActivityOrders, addActivityOrder, updateActivityOrder, deleteActivityOrder, getWriteOffCode, writeOffOrder } from "@/api/content";
import SelectActivity from "@/components/selectActivity.vue";
import SelectUser from "@/components/selectUser.vue";
import OrderParticipantDialog from "@/components/orderParticipantDialog.vue";

export default {
  name: "ActivityOrder",
  components: {
    SelectActivity,
    SelectUser,
    OrderParticipantDialog
  },
  data() {
    return {
      searchForm: {
        activityTitle: "",
        orderTradeId: "",
        participantsName: "",
        userId: "",
      },
      tableData: [],
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 订单弹窗
      orderDialog: {
        visible: false,
        isEdit: false,
        editId: null,
        form: {
          activityId: "",
          buyerId: "",
          mobile: "",
          payStatus: 0,
          payTime: "",
          payWay: "",
          refundStatus: 0,
          refundTime: "",
          tradeInfo: "",
          tradeNumber: 1,
          tradeTime: "",
        },
      },
      // 参与人弹窗
      participantDialog: {
        visible: false,
        orderId: null,
        orderTradeId: null,
        votesGoods: null
      },
      // 选择活动/用户弹窗
      selectActivityVisible: false,
      selectUserVisible: false,
      selectedActivity: null,
      selectedUser: null,
      // 核销码预览弹窗
      qrCodePreviewDialog: {
        visible: false,
        imageUrl: "",
        orderId: null
      },
      writeOffLoading: false,
      // 表单验证规则
      orderRules: {
        activityId: [
          { required: true, message: '请选择活动', trigger: 'change' }
        ],
        buyerId: [
          { required: true, message: '请选择购买者', trigger: 'change' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        payStatus: [
          { required: true, message: '请选择支付状态', trigger: 'change' }
        ],
        tradeNumber: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    totalPrice() {
      if (this.selectedActivity && this.orderDialog.form.tradeNumber) {
        return (this.selectedActivity.paymentAmount || 0) * this.orderDialog.form.tradeNumber;
      }
      return 0;
    },
    selectedActivityDisplay: {
      get() {
        return this.selectedActivity ? `${this.selectedActivity.title}（${this.selectedActivity.id}）` : '';
      },
      set() {
        // 不允许直接设置，只能通过选择活动弹窗设置
      }
    },
    selectedUserDisplay: {
      get() {
        return this.selectedUser ? `${this.selectedUser.nickname}（${this.selectedUser.userId}）` : '';
      },
      set() {
        // 不允许直接设置，只能通过选择用户弹窗设置
      }
    }
  },
  mounted() {
    // 检查路由query参数中是否有userId，如果有就赋值给筛选参数
    if (this.$route.query.userId) {
      this.searchForm.userId = this.$route.query.userId;
    }
    this.getData();
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      if (this.searchForm.activityTitle) {
        params.activityTitle = this.searchForm.activityTitle;
      }
      if (this.searchForm.orderTradeId) {
        params.orderTradeId = this.searchForm.orderTradeId;
      }
      if (this.searchForm.participantsName) {
        params.participantsName = this.searchForm.participantsName;
      }
      if (this.searchForm.userId) {
        params.userId = this.searchForm.userId;
      }

      return params;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const response = await getActivityOrders(params);

        if (response && response.data) {
          this.tableData = response.data.rows || [];

          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取活动订单数据失败:', error);
        this.$message.error('获取活动订单数据失败');
      }
    },
    // 解析参与人信息
    parseParticipants(tradeInfo) {
      try {
        if (!tradeInfo) return [];
        const info = JSON.parse(tradeInfo);
        return info.participants || [];
      } catch (error) {
        return [];
      }
    },
    // 获取参与人数量
    getParticipantCount(row) {
      // 这里可以根据实际情况返回参与人数量
      // 如果有专门的字段存储参与人数量，可以直接返回
      // 否则可以通过解析tradeInfo或者其他方式获取
      return row.tradeNumber || 1;
    },
    // 获取支付状态类型
    getPayStatusType(tradeStatus) {
      const statusMap = {
        0: 'info',    // 待支付
        1: 'success', // 已支付
        2: 'warning', // 已取消
        3: 'danger'   // 已退款
      };
      return statusMap[tradeStatus] || 'info';
    },
    // 获取支付状态文本
    getPayStatusText(tradeStatus) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已取消',
        3: '已退款'
      };
      return statusMap[tradeStatus] || '未知';
    },
    // 获取核销状态类型
    getWriteOffStatusType(writeOffStatus) {
      const statusMap = {
        0: 'warning', // 待核销
        1: 'success'  // 已核销
      };
      return statusMap[writeOffStatus] || 'warning';
    },
    // 获取核销状态文本
    getWriteOffStatusText(writeOffStatus) {
      const statusMap = {
        0: '待核销',
        1: '已核销'
      };
      return statusMap[writeOffStatus] || '待核销';
    },
    // 获取支付方式文本
    getPayWayText(payWay) {
      const payWayMap = {
        1: '支付宝',
        2: '微信',
        3: '衫德',
        4: '余额'
      };
      return payWayMap[payWay] || '-';
    },
    // 计算总价
    calculateTotal() {
      // 总价会通过computed自动计算
    },
    // 显示新增订单弹窗
    showAddOrder() {
      this.orderDialog.visible = true;
      this.orderDialog.isEdit = false;
      this.orderDialog.editId = null;
      this.orderDialog.form = {
        activityId: "",
        buyerId: "",
        mobile: "",
        payStatus: 0,
        payTime: "",
        payWay: "",
        refundStatus: 0,
        refundTime: "",
        tradeInfo: "",
        tradeNumber: 1,
        tradeTime: new Date(),
      };
      this.selectedActivity = null;
      this.selectedUser = null;
      this.$nextTick(() => {
        this.$refs.orderForm?.clearValidate();
      });
    },
    // 显示编辑订单弹窗
    showEditOrder(row) {
      this.orderDialog.visible = true;
      this.orderDialog.isEdit = true;
      this.orderDialog.editId = row.id;
      this.orderDialog.form = {
        activityId: row.tradeGoods || "",
        buyerId: row.tradeUser || "",
        mobile: row.mobile || "",
        payStatus: row.tradeStatus || 0,
        payTime: row.payTime || "",
        payWay: row.payWay || "",
        refundStatus: row.refundStatus || 0,
        refundTime: row.refundTime || "",
        tradeInfo: row.tradeInfo || "",
        tradeNumber: row.tradeNumber || 1,
        tradeTime: row.tradeTime || "",
      };
      // 设置编辑时的选中活动和用户信息
      if (row.tradeGoods && row.tradeGoodsName) {
        this.selectedActivity = {
          id: row.tradeGoods,
          title: row.tradeGoodsName,
          paymentAmount: row.tradePrice || 0
        };
      } else {
        this.selectedActivity = null;
      }

      if (row.tradeUser) {
        this.selectedUser = {
          userId: row.tradeUser,
          nickname: row.tradeUserName || `用户`, // 如果没有用户名，使用用户ID
          mobile: row.mobile || ""
        };
      } else {
        this.selectedUser = null;
      }

      this.$nextTick(() => {
        this.$refs.orderForm?.clearValidate();
      });
    },
    // 保存订单
    saveOrder() {
      this.$refs.orderForm.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              tradeGoods: this.orderDialog.form.activityId,
              tradeGoodsName: this.selectedActivity?.title || "",
              tradeUser: this.orderDialog.form.buyerId,
              mobile: this.orderDialog.form.mobile,
              tradeStatus: this.orderDialog.form.payStatus,
              payWay: this.orderDialog.form.payWay,
              payTime: this.orderDialog.form.payTime,
              refundStatus: this.orderDialog.form.refundStatus,
              refundTime: this.orderDialog.form.refundTime,
              tradeInfo: this.orderDialog.form.tradeInfo,
              tradeNumber: this.orderDialog.form.tradeNumber,
              tradePrice: this.selectedActivity?.paymentAmount || 0,
              tradeMoney: this.totalPrice,
              tradeTime: this.orderDialog.form.tradeTime,
              writeOffStatus: this.orderDialog.form.payStatus === 1 ? 0 : null, // 已支付的订单设置为待核销
            };

            if (this.orderDialog.isEdit) {
              params.id = this.orderDialog.editId;
              await updateActivityOrder(params);
              this.$message.success('编辑订单成功');
            } else {
              await addActivityOrder(params);
              this.$message.success('新增订单成功');
            }

            this.orderDialog.visible = false;
            this.getData();
          } catch (error) {
            console.error('保存订单失败:', error);
            this.$message.error('保存订单失败');
          }
        }
      });
    },
    // 显示选择活动弹窗
    showSelectActivity() {
      this.selectActivityVisible = true;
    },
    // 处理活动选择
    handleActivitySelect(activity) {
      this.selectedActivity = activity;
      this.orderDialog.form.activityId = activity.id;
    },
    // 显示选择用户弹窗
    showSelectUser() {
      this.selectUserVisible = true;
    },
    // 处理用户选择
    handleUserSelect(users) {
      if (users && users.length > 0) {
        this.selectedUser = users[0];
        this.orderDialog.form.buyerId = users[0].userId;
        this.orderDialog.form.mobile = users[0].mobile || "";
      }
    },
    // 清除活动选择
    clearActivity() {
      this.selectedActivity = null;
      this.orderDialog.form.activityId = "";
    },
    // 清除用户选择
    clearUser() {
      this.selectedUser = null;
      this.orderDialog.form.buyerId = "";
      this.orderDialog.form.mobile = "";
    },
    // 显示修改参与人弹窗
    showEditParticipants(row) {
      this.participantDialog.visible = true;
      this.participantDialog.orderId = row.id;
      this.participantDialog.orderTradeId = row.orderTradeId;
      this.participantDialog.votesGoods = row.tradeGoods;
    },

    // 显示核销码
    async showWriteOffCode(row) {
      try {
        const response = await getWriteOffCode({ id: row.id });
        if (response && response.data) {
          this.qrCodePreviewDialog.visible = true;
          this.qrCodePreviewDialog.imageUrl = response.data;
          this.qrCodePreviewDialog.orderId = row.id;
        } else {
          this.$message.error('获取核销码失败');
        }
      } catch (error) {
        console.error('获取核销码失败:', error);
        this.$message.error('获取核销码失败');
      }
    },
    // 核销订单
    async handleWriteOff() {
      if (!this.qrCodePreviewDialog.orderId) {
        this.$message.error('订单ID不存在');
        return;
      }

      this.$confirm('确定要核销此订单吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          this.writeOffLoading = true;
          await writeOffOrder({ id: this.qrCodePreviewDialog.orderId });
          this.$message.success('核销成功');
          this.qrCodePreviewDialog.visible = false;
          this.getData(); // 刷新列表
        } catch (error) {
          console.error('核销失败:', error);
          this.$message.error('核销失败');
        } finally {
          this.writeOffLoading = false;
        }
      }).catch(() => {
        // 用户取消
      });
    },
    // 删除订单
    handleDelete(row) {
      this.$confirm('确定要删除此订单吗？删除后无法恢复！', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await deleteActivityOrder({ id: row.id });
          this.$message.success('删除订单成功');
          this.getData();
        } catch (error) {
          console.error('删除订单失败:', error);
          this.$message.error('删除订单失败');
        }
      }).catch(() => {
        // 用户取消
      });
    }
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.participant-info {
  font-size: 12px;
  line-height: 1.4;
  margin-bottom: 2px;
}

.order-info {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.total-price {
  color: #f56c6c;
  font-weight: bold;
}



.total-display {
  margin-top: 10px;
  font-size: 14px;

  .total-price {
    color: #f56c6c;
    font-weight: bold;
    font-size: 16px;
  }
}



::v-deep .el-date-editor {
  margin-right: 10px;
  width: 300px;
}

::v-deep .el-input-number {
  width: 150px;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-textarea {
  width: 100%;
}

.mb10 {
  margin-bottom: 10px;
}

// 核销码相关样式
.qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.qr-code-thumbnail {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
    transform: scale(1.05);
  }
}

.qr-code-preview {
  text-align: center;
  padding: 20px;

  img {
    max-width: 100%;
    max-height: 400px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
}
</style>